const formatTime = date => {
  const tyear = date.getFullYear()
  const tmonth = date.getMonth() + 1
  const tday = date.getDate()
  const thour = date.getHours()
  const tminute = date.getMinutes()

  return [tyear, tmonth, tday].map(formatNumber).join('/')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatTimeThr = (number, format) => {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

const formatTimeTwo =(number, format) => {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

const checkLogin = function () {
  let res = getApp().globalData.access_token ? true : false;
  let res1 = getApp().globalData.isLog;
  let res2 = res && res1;
  if (res2) {
    let newTime = Math.round(new Date() / 1000);
    if (getApp().globalData.expiresTime < newTime) return false;
  }
  return res2;
}

const authLogin = function () {
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: 'cache_key',
      success(res) {
        wxgetUserInfo().then(userInfo => {
          userInfo.cache_key = res.data;
          return resolve(userInfo);
        }).catch(res => {
          return reject(res);
        })
      },
      fail() {
        getCodeLogin((code) => {
          wxgetUserInfo().then(userInfo => {
            userInfo.code = code;
            return resolve(userInfo);
          }).catch(res => {
            return reject(res);
          })
        });
      }
    });
  })
}

const wxgetUserInfo = function () {
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      lang: 'zh_CN',
      success(res) {
        resolve(res);
      },
      fail(res) {
        reject(res);
      }
    })
  });
}

const getCodeLogin = function (successFn) {
  wx.login({
    success(res) {
      successFn(res);
    }
  })
}

/**
   * opt  object | string
   * to_url object | string
   * 例:
   * this.Tips('/pages/test/test'); 跳转不提示
   * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
   * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
   * tab=1 一定时间后跳转至 table上
   * tab=2 一定时间后跳转至非 table上
   * tab=3 一定时间后返回上页面
   * tab=4 关闭所有页面跳转至非table上
   * tab=5 关闭当前页面跳转至table上
   */
const Tips = function (opt, to_url) {
  if (typeof opt == 'string') {
    to_url = opt;
    opt = {};
  }
  var title = opt.title || '', icon = opt.icon || 'none', endtime = opt.endtime || 2000;
  if (title) wx.showToast({ title: title, icon: icon, duration: endtime })
  if (to_url != undefined) {
    if (typeof to_url == 'object') {
      var tab = to_url.tab || 1, url = to_url.url || '';
      switch (tab) {
        case 1:
          //一定时间后跳转至 table
          setTimeout(function () {
            wx.switchTab({
              url: url
            })
          }, endtime);
          break;
        case 2:
          //跳转至非table页面
          setTimeout(function () {
            wx.navigateTo({
              url: url,
            })
          }, endtime);
          break;
        case 3:
          //返回上页面
          setTimeout(function () {
            wx.navigateBack({
              delta: parseInt(url),
            })
          }, endtime);
          break;
        case 4:
          //关闭当前所有页面跳转至非table页面
          setTimeout(function () {
            wx.reLaunch({
              url: url,
            })
          }, endtime);
          break;
        case 5:
          //关闭当前页面跳转至非table页面
          setTimeout(function () {
            wx.redirectTo({
              url: url,
            })
          }, endtime);
          break;
      }

    } else if (typeof to_url == 'function') {
      setTimeout(function () {
        to_url && to_url();
      }, endtime);
    } else {
      //没有提示时跳转不延迟
      setTimeout(function () {
        wx.navigateTo({
          url: to_url,
        })
      }, title ? endtime : 0);
    }
  }
}

const chekWxLogin = function () {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          return reject({ authSetting: false });
        } else {
          wx.getStorage({
            key: 'cache_key',
            success(res) {
              if (checkLogin()) {
                return resolve({ userinfo: getApp().globalData.userInfo, isLogin: true });
              } else {
                wxgetUserInfo().then(userInfo => {
                  userInfo.cache_key = res.data;
                  return resolve({ userInfo: userInfo, isLogin: false });
                }).catch(res => {
                  return reject(res);
                })
              }
            },
            fail() {
              getCodeLogin((code) => {
                wxgetUserInfo().then(userInfo => {
                  userInfo.code = code;
                  return resolve({ userInfo: userInfo, isLogin: false });
                }).catch(res => {
                  return reject(res);
                })
              });
            }
          })

        }
      },
      fail(res) {
        return reject(res);
      }
    })
  })
}

module.exports = {
  formatTime: formatTime,
  formatTimeTwo: formatTimeTwo,
  formatTimeThr: formatTimeThr,
  checkLogin: checkLogin,
  authLogin: authLogin,
  getCodeLogin: getCodeLogin,
  wxgetUserInfo: wxgetUserInfo,
  Tips: Tips,
  chekWxLogin: chekWxLogin
}
